<template>
  <div class="map-container">
    <!-- 地图容器 -->
    <div id="mapContainer" class="map"></div>
    
    <!-- 控制按钮面板 -->
    <div class="control-panel">
      <button @click="startDrawFence" :disabled="isDrawing">开始绘制围栏</button>
      <button @click="finishDrawFence" :disabled="!isDrawing || vertices.length < 3">完成绘制</button>
      <button @click="cancelDrawFence" :disabled="!isDrawing">取消绘制</button>
      <button @click="clearFence" :disabled="!currentFence">清除围栏</button>
      <button @click="addVehicle">添加车辆</button>
      <button @click="checkVehicleStatus">检查车辆状态</button>
    </div>
    
    <!-- 状态信息 -->
    <div class="status-info" v-if="vehicleStatus">
      {{ vehicleStatus }}
    </div>
  </div>
</template>

<script setup>
import { onMounted, ref, onUnmounted } from 'vue';

// 地图实例
let map = null;
// 当前电子围栏实例
let currentFence = null;
// 临时绘制的线条和点
let tempLine = null;
let tempMarkers = [];
// 车辆标记实例
let vehicleMarker = null;
// 地图点击事件监听函数引用
let mapClickHandler = null;

// 状态变量
const isDrawing = ref(false);
const vehicleStatus = ref('');
const vertices = ref([]); // 手动管理顶点数组
const vehiclePosition = ref({
  lng: 116.397470,
  lat: 39.908823
});

// 初始化地图
const initMap = () => {
  if (!window.AMap) {
    console.error('高德地图SDK未加载');
    return;
  }
  
  // 创建地图实例
  map = new window.AMap.Map('mapContainer', {
    zoom: 13,
    center: [vehiclePosition.value.lng, vehiclePosition.value.lat],
    resizeEnable: true
  });
  
  // 添加地图控件
  map.addControl(new window.AMap.ToolBar({
    position: 'RB'
  }));
};

// 开始绘制围栏 - 不依赖PolygonEditor，手动管理顶点
const startDrawFence = () => {
  if (isDrawing.value) return;
  
  // 重置状态
  resetDrawingState();
  
  isDrawing.value = true;
  vertices.value = [];
  
  // 创建地图点击事件处理函数
  mapClickHandler = (e) => {
    try {
      // 获取点击位置的经纬度
      const { lng, lat } = e.lnglat;
      const point = [lng, lat];
      
      // 添加顶点到数组
      vertices.value.push(point);
      
      // 在地图上标记顶点
      const marker = new window.AMap.Marker({
        position: point,
        icon: new window.AMap.Icon({
          size: new window.AMap.Size(10, 10),
          image: 'https://a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png',
          imageSize: new window.AMap.Size(10, 10)
        }),
        zIndex: 100
      });
      map.add(marker);
      tempMarkers.push(marker);
      
      // 更新临时线条
      updateTempLine();
      
      // 显示提示信息
      vehicleStatus.value = `已添加${vertices.value.length}个顶点，至少需要3个顶点才能完成绘制`;
    } catch (error) {
      console.error('添加顶点失败:', error);
      vehicleStatus.value = `添加顶点失败: ${error.message}`;
    }
  };
  
  // 绑定地图点击事件
  map.on('click', mapClickHandler);
  vehicleStatus.value = '请在地图上点击添加围栏顶点';
};

// 更新临时线条
const updateTempLine = () => {
  // 移除之前的临时线条
  if (tempLine) {
    map.remove(tempLine);
    tempLine = null;
  }
  
  // 至少需要2个点才能绘制线条
  if (vertices.value.length >= 2) {
    // 创建临时线条
    tempLine = new window.AMap.Polyline({
      path: vertices.value,
      strokeColor: '#FF0000',
      strokeWeight: 2,
      zIndex: 50
    });
    map.add(tempLine);
  }
};

// 完成绘制围栏
const finishDrawFence = () => {
  if (!isDrawing.value || vertices.value.length < 3) return;
  
  // 移除临时元素
  resetDrawingState(false);
  
  // 创建闭合的多边形围栏
  currentFence = new window.AMap.Polygon({
    path: [...vertices.value, vertices.value[0]], // 闭合多边形
    strokeColor: '#FF0000',
    strokeWeight: 3,
    fillColor: 'rgba(255, 0, 0, 0.2)',
    zIndex: 50
  });
  
  map.add(currentFence);
  isDrawing.value = false;
  vehicleStatus.value = `围栏绘制完成，共${vertices.value.length}个顶点`;
  setTimeout(() => {
    vehicleStatus.value = '';
  }, 3000);
};

// 取消绘制围栏
const cancelDrawFence = () => {
  if (!isDrawing.value) return;
  
  // 重置绘制状态，包括清除临时元素
  resetDrawingState(true);
  isDrawing.value = false;
  vehicleStatus.value = '绘制已取消';
  setTimeout(() => {
    vehicleStatus.value = '';
  }, 2000);
};

// 重置绘制状态
const resetDrawingState = (clearVertices = true) => {
  // 解绑地图点击事件
  if (mapClickHandler) {
    map.off('click', mapClickHandler);
    mapClickHandler = null;
  }
  
  // 移除临时线条
  if (tempLine) {
    map.remove(tempLine);
    tempLine = null;
  }
  
  // 移除临时标记
  if (tempMarkers.length > 0) {
    map.remove(tempMarkers);
    tempMarkers = [];
  }
  
  // 清空顶点数组
  if (clearVertices) {
    vertices.value = [];
  }
};

// 清除围栏
const clearFence = () => {
  if (currentFence) {
    map.remove(currentFence);
    currentFence = null;
    vehicleStatus.value = '围栏已清除';
    setTimeout(() => {
      vehicleStatus.value = '';
    }, 2000);
  }
};

// 添加车辆标记
const addVehicle = () => {
  if (vehicleMarker) {
    map.remove(vehicleMarker);
  }
  
  const icon = new window.AMap.Icon({
    size: new window.AMap.Size(40, 40),
    image: 'https://a.amap.com/jsapi_demos/static/demo-center/icons/car.png',
    imageSize: new window.AMap.Size(40, 40)
  });
  
  vehicleMarker = new window.AMap.Marker({
    position: [vehiclePosition.value.lng, vehiclePosition.value.lat],
    icon: icon,
    anchor: 'center',
    title: '车辆'
  });
  
  map.add(vehicleMarker);
  vehicleStatus.value = '车辆已添加';
  setTimeout(() => {
    vehicleStatus.value = '';
  }, 2000);
};

// 检查车辆是否在围栏内
const checkVehicleStatus = () => {
  if (!currentFence) {
    vehicleStatus.value = '请先绘制电子围栏';
    return;
  }
  
  if (!vehicleMarker) {
    vehicleStatus.value = '请先添加车辆';
    return;
  }
  
  try {
    const path = currentFence.getPath();
    const point = vehicleMarker.getPosition();
    const isInside = window.AMap.GeometryUtil.isPointInRing(point, path);
    
    vehicleStatus.value = isInside ? '车辆在围栏内' : '车辆在围栏外';
  } catch (error) {
    console.error('检查车辆状态失败:', error);
    vehicleStatus.value = '检查车辆状态失败';
  } finally {
    setTimeout(() => {
      vehicleStatus.value = '';
    }, 3000);
  }
};

// 组件卸载时清理资源
onUnmounted(() => {
  if (map) {
    // 移除事件监听
    if (mapClickHandler) {
      map.off('click', mapClickHandler);
    }
    // 移除所有覆盖物
    map.removeAllOverlays();
    // 销毁地图实例
    map.destroy();
  }
  currentFence = null;
  vehicleMarker = null;
  tempLine = null;
  tempMarkers = [];
});

// 组件挂载时初始化地图
onMounted(() => {
  const script = document.createElement('script');
  const key = '7fac11790025fa9da05e739566ca7af8'; // 替换为你的API密钥
  // 只加载必要的基础插件
  script.src = `https://webapi.amap.com/maps?v=2.0&key=${key}&plugin=AMap.ToolBar,AMap.GeometryUtil`;
  script.onload = initMap;
  document.head.appendChild(script);
});
</script>

<style scoped>
.map-container {
  position: relative;
  width: 100%;
  height: 100vh;
}

.map {
  width: 100%;
  height: 100%;
}

.control-panel {
  position: absolute;
  top: 20px;
  left: 20px;
  z-index: 1000;
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  padding: 10px;
  background-color: white;
  border-radius: 4px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

button {
  padding: 8px 16px;
  background-color: #1677ff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}

button:disabled {
  background-color: #cccccc;
  cursor: not-allowed;
}

button:hover:not(:disabled) {
  background-color: #0f5fcf;
}

.status-info {
  position: absolute;
  bottom: 20px;
  left: 20px;
  z-index: 1000;
  padding: 10px 16px;
  background-color: rgba(0, 0, 0, 0.7);
  color: white;
  border-radius: 4px;
}
</style>
    